using System;
using Infinity.Common;

namespace Infinity.API.Core
{
	public class ConditionCodeAction : CodeAction
	{
		public CodeAction Action { get; protected set; }

		public Func<bool> Condition { get; protected set; }

		public ConditionCodeAction(Func<bool> condition, CodeAction action)
		{
			Condition = Ensure.NotNull("condition", condition);
			Action = Ensure.NotNull("action", action);
		}

		public override void Run()
		{
			OnExecuting(this);

			OnConditionExecuting(this);
			var result = Condition();
			OnConditionExecuted(this);

			if (result)
				Action.Run();

			OnExecuted(this);
		}

		public event Action<ConditionCodeAction> ConditionExecuting;

		public void OnConditionExecuting(ConditionCodeAction obj)
		{
			Action<ConditionCodeAction> handler = ConditionExecuting;
			if (handler != null) handler(obj);
		}

		public event Action<ConditionCodeAction> ConditionExecuted;

		public void OnConditionExecuted(ConditionCodeAction obj)
		{
			Action<ConditionCodeAction> handler = ConditionExecuted;
			if (handler != null) handler(obj);
		}
	}
}